﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrmContacto.Contracts;
using CrmContacto.Contracts.Contracts.Search;
using CrmContacto.Contracts.Enums;
using CrmContacto.WebApp.Code.InnerClasses;
using Web.CrmContacto.Code;
using Web.CrmContacto.Code.Security;
using Web.Framework;
using Web.Framework.Helpers;
using Web.Framework.Misc;
using Web.Framework.Search;
using Web.Framework.Translate;
using CrmContacto.WebApp.Code.InnerClasses.FrontEnd;
using CrmContacto.WebApp.ServiceReferenceApiAuth;
using System.Text;
using CrmContacto.Contracts.Contracts;

namespace Web.CrmContacto.App
{
    public partial class CustomerSearch : BasePage
    {
        private SortDirection SortDirectionViewState
        {
            get
            {
                if (ViewState["SortDirectionViewState"] == null)
                    return SortDirection.Ascending;
                else
                    return (SortDirection)ViewState["SortDirectionViewState"];
            }
            set
            {
                ViewState["SortDirectionViewState"] = value;
            }
        }

        private string SortExpressionViewState
        {
            get
            {
                return Convert.ToString(ViewState["SortExpressionViewState"]);
            }
            set
            {
                ViewState["SortExpressionViewState"] = value;
            }
        }

        private CustomerSearchParam CustomerSearchParamSession
        {
            get
            {
                return (CustomerSearchParam)StoreHelper.GetObject(MiscClass.CustomerSearchParamCacheKey);
            }
            set
            {
                StoreHelper.StoreObject(MiscClass.CustomerSearchParamCacheKey, value);
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        LinkButton crearContactoButton = new LinkButton();
        LinkButton importarContactosButton = new LinkButton();
        LinkButton agregarContactosAListaButton = new LinkButton();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.GridCustomer.PagerSettings.Mode = PagerButtons.NumericFirstLast;

            NavigationContext navContext = null;
            if (this.Request.QueryString["useContext"] != null)
            {
                navContext = base.NavigationContext;
            }

            crearContactoButton.ID = "BoSearchContactoCmdCrearContacto";
            crearContactoButton.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdCrearContacto"];
            crearContactoButton.Click += new EventHandler(crearContactoButton_Click);
            actionButtons.Add(crearContactoButton);

            importarContactosButton.ID = "BoSearchContactoCmdImportarContacto";
            importarContactosButton.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdImportarContacto"];
            importarContactosButton.Click += new EventHandler(importarContactosButton_Click);
            actionButtons.Add(importarContactosButton);

            agregarContactosAListaButton.ID = "BoSearchContactoCmdAgregarAListaDistribucion";
            agregarContactosAListaButton.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdAgregarAListaDistribucion"];
            agregarContactosAListaButton.Click += new EventHandler(agregarContactosAListaButton_Click);
            actionButtons.Add(agregarContactosAListaButton);
            lnkAsociar.Text = agregarContactosAListaButton.Text;
            lnkAsociar.Click += new EventHandler(agregarContactosAListaButton_Click);

            if (navContext != null && navContext.AgregandoContactosAListaDistribucion)
            {
                TitleNavContext.Visible = true;
                lblContexto.Text = LocalizationProvider.Instance["Bo.SearchContacto.Context.ListaDistribucion"];
            }

            base.LoadContextActions(actionButtons);
        }

        void importarContactosButton_Click(object sender, EventArgs e)
        {
            try
            {
                SetThisPageToGoBack();
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlImportarContactos, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void agregarContactosACategoria_Click(object sender, EventArgs e)
        {
            try
            {
                GudarClientesSeleccionadosEnContexto();
                NavigationContext navContext = null;
                navContext = base.NavigationContext;
                SetThisPageToGoBack();

                navContext.AgregandoContactosACategorias = true;
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCategoriaList, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void SetThisPageToGoBack()
        {
            this.NavigationContext.UrlToGoBack = Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCustomerSearch;
        }

        private void agregarContactosAListaButton_Click(object sender, EventArgs e)
        {
            try
            {
                GudarClientesSeleccionadosEnContexto();
                NavigationContext navContext = null;
                if (this.Request.QueryString["useContext"] != null)
                {
                    navContext = base.NavigationContext;
                }

                if (navContext != null && navContext.AgregandoContactosAListaDistribucion)
                {
                    // Si esta agregando a una lista => los mando directo a la lista de dsitribución
                    Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlListaDeDistribucionEdit + string.Format("?Id={0}&loadingContacts=1", navContext.ListaDistribucionId.Value), true);
                }
                else
                {
                    // Si no hay una lista en contexto, los mando igual a una lista nueva
                    Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlListaDeDistribucionEdit + "?loadingContacts=1", true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void crearContactoButton_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCustomerEdit, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        List<ColumnasParaGrilla> columnasParaGrillaListCurrent;

        private List<ColumnasParaGrilla> columnsDefault = new List<ColumnasParaGrilla>();

        private void LoadColumnasDefault()
        {
            int i = 2;
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Email", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.Email"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Nombre", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.Nombre"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Apellido", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.Apellido"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "TipoDocumentoId", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.TipoDocumento"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "NroDocumento", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.DocumentoShort"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "EstadoEmail", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.EstadoEmail"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "FechaUltimaCompra", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.UltimaCompra"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "OrigenId", Visible = true, ColumnDescription = LocalizationProvider.Instance["Contacto.Origen"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "OrigenPuntoDeVentaId", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.OrigenPuntoDeVentaId"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "CumpleDia", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.CumpleanosDia"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "CumpleMes", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.CumpleanosMes"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "CumpleAnio", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.CumpleanosAnio"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Nacionalidad", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Nacionalidad"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "ProvinciaId", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Provincia"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Domicilio", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Domicilio"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "CodigoPostal", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.CodigoPostal"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Estado", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Estado"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Telefono", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Telefono"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "NroCredencial", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Credencial"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "AuditFechaCreacion", Visible = false, ColumnDescription = LocalizationProvider.Instance["Auditoria.FechaCreacion"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "Sexo", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Sexo"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "AuditUserNameCreacion", Visible = false, ColumnDescription = LocalizationProvider.Instance["Auditoria.UsuarioCreador"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "CategoriasDisplay", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.Categoria"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "CantidadHijos", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.CantidadHijos"] });
            columnsDefault.Add(new ColumnasParaGrilla() { PosicionDestino = i, PosicionOriginal = i++, ColumnName = "EdadHijoMenor", Visible = false, ColumnDescription = LocalizationProvider.Instance["Contacto.EdadHijoMenor"] });
        }

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
            LoadColumnasDefault();
            List<ColumnasParaGrilla> columnasParaGrillaList = new List<ColumnasParaGrilla>();

            string strOrdenColumnas = this.hidOrdenDeColumnas.Value;
            if (!String.IsNullOrEmpty(strOrdenColumnas)) // podría controlar el click del botón aplicar cambios
            {
                if (strOrdenColumnas == "default")
                {
                    // Guardo el default en sessión
                    columnasParaGrillaList.AddRange(columnsDefault);
                    StoreHelper.StoreObject(MiscClass.CustomerColumnsKey, columnasParaGrillaList);
                    this.hidOrdenDeColumnas.Value = string.Empty; // procesado el evento
                }
                else
                {
                    // aplicar cambios de columnas
                    string[] columnasCampos = strOrdenColumnas.Split('#');

                    // Registro como quiere las columnas el usuario
                    int i = 2;
                    foreach (string campo in columnasCampos)
                    {
                        string[] campoSplit = campo.Split('+');
                        ColumnasParaGrilla columnaParaGrilla = new ColumnasParaGrilla();
                        columnaParaGrilla.ColumnName = campoSplit[0].Replace("chk", "");
                        columnaParaGrilla.Visible = campoSplit[1] == "true";
                        columnaParaGrilla.PosicionDestino = i;
                        columnaParaGrilla.PosicionOriginal = columnsDefault.Where(c => c.ColumnName == columnaParaGrilla.ColumnName).Single().PosicionOriginal;
                        columnaParaGrilla.ColumnDescription = columnsDefault.Where(c => c.ColumnName == columnaParaGrilla.ColumnName).Single().ColumnDescription;
                        columnasParaGrillaList.Add(columnaParaGrilla);
                        i++;
                    }

                    StoreHelper.StoreObject(MiscClass.CustomerColumnsKey, columnasParaGrillaList);
                    this.hidOrdenDeColumnas.Value = string.Empty; // procesado el evento
                }
            }
            else
            {
                // Si el string es nulo, controlo que este en session el orden de las columnas
                var obj = StoreHelper.GetObject(MiscClass.CustomerColumnsKey);
                if (obj != null)
                {
                    columnasParaGrillaList = (List<ColumnasParaGrilla>)obj;
                }
                else
                {
                    // Guardo el default en sessión
                    columnasParaGrillaList.AddRange(columnsDefault);
                    StoreHelper.StoreObject(MiscClass.CustomerColumnsKey, columnasParaGrillaList);
                }
            }

            columnasParaGrillaListCurrent = columnasParaGrillaList;

            // Una vez que sé qeu columas dibujar las dibujo, primero clono las actuales
            DataControlFieldCollection columnasClonadas = this.GridCustomer.Columns.CloneFields();

            // Por cada columna reordeno
            foreach (ColumnasParaGrilla columnaParaGrilla in columnasParaGrillaList)
            {
                if (columnaParaGrilla.Visible)
                {
                    if (columnaParaGrilla.PosicionOriginal != columnaParaGrilla.PosicionDestino)
                    {
                        this.GridCustomer.Columns.RemoveAt(columnaParaGrilla.PosicionDestino);
                        this.GridCustomer.Columns.Insert(columnaParaGrilla.PosicionDestino, columnasClonadas[columnaParaGrilla.PosicionOriginal]);
                    }
                }
                else
                {
                    this.GridCustomer.Columns[columnaParaGrilla.PosicionDestino].Visible = false;
                }
            }

            this.repeaterColumnOrderSelector.DataSource = columnasParaGrillaListCurrent;
            this.repeaterColumnOrderSelector.DataBind();

            // Tengo que cargar el draggable de ventanas ordenado
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                HasPermissionToSeeMe(CrmSecurity.CUSTOMERSEARCH_VIEW);

                if (this.Request.Form["selectAllRows"] != null)
                {
                    //bool selectAll = this.Request.Form["selectAllRows"] == "true";
                    //SeleccionarTodos(selectAll);
                    //this.hidCheckedRows.Value = string.Empty;
                }
                else
                {
                    RememberOldValues();
                    // asigno el unique id para poder llamarlos desde javascript
                    this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.UniqueID);
                    this.lnkDummyRefreshSelectedGridChecks.Attributes.Add("aspnetid", this.lnkDummyRefreshSelectedGridChecks.UniqueID);
                    this.lnkAplicarOrdenColumnas.Attributes.Add("aspnetid", this.lnkAplicarOrdenColumnas.UniqueID);

                    this.pnlResults.CssClass = "displayNone";
                    this.imgExpandResults.ImageUrl = "/Images/icon_blockcollapsed.png";

                    if (!this.IsPostBack)
                    {
                        LoadCbos();
                        LoadContextSearch();

                        // Si vuelvo de asignar categorías
                        if (this.Request.QueryString["search"] != null)
                        {
                            if (this.Request.QueryString["search"] == "1")
                            {
                                Buscar();
                            }
                        }

                        if (this.Request.QueryString["addingCategoriasOk"] != null)
                        {
                            base.NavigationContext.AgregandoContactosACategorias = false;
                            if (this.Request.QueryString["addingCategoriasOk"] == "1")
                            {
                                this.masterPage.ShowMessage(LocalizationProvider.Instance["Bo.Messages.ContactoAgregadoACategoria"], WebMessageType.Notification);
                            }
                        }
                    }

                    FiltroPanelVisibility();
                    GridMenuOptions();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected override void ApplySecurity()
        {
            HasPermissionToSeeMe(CrmSecurity.CUSTOMERSEARCH_VIEW);
          
            crearContactoButton.Visible = HasPermissionFor(CrmSecurity.CUSTOMER_CREATE);
            importarContactosButton.Visible = HasPermissionFor(CrmSecurity.CUSTOMER_IMPORT);

            var navContext = base.NavigationContext;
            if (navContext != null && navContext.AgregandoContactosAListaDistribucion)
            {
                A1.Visible = false;
                lnkAsociar.Visible =
                agregarContactosAListaButton.Visible = HasPermissionFor(CrmSecurity.CUSTOMER_ADDTO_DISTRIBUTIONLIST);
            }
            else
            {
                A1.Visible = true;
                lnkAsociar.Visible = false;
                agregarContactosAListaButton.Visible = false;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        private void LoadContextSearch()
        {
            if (CustomerSearchParamSession != null)
            {
                // recargo los filtros      

                LoadControlsFromSearchContext();

                //BindToGrid();
                //RePopulateValues();
            }
        }

        private void GridMenuOptions()
        {
            LinkButton btnLink = new LinkButton();
            if (HasPermissionFor(CrmSecurity.CUSTOMER_DELETE))
            {
                btnLink = new LinkButton();
                btnLink.ID = "lnkGridWizardEliminarContactos";
                btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                btnLink.CssClass = "menu_item_cmd";
                btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdEliminarContacto"];
                btnLink.Click += new EventHandler(btnLinkBorrarContactos_Click);
                btnLink.Visible = HasPermissionFor(CrmSecurity.CUSTOMER_DELETE);
                pnlGridWizardMenu.Controls.Add(btnLink);
            }

            if (HasPermissionFor(CrmSecurity.CUSTOMER_EXPORT_EXCEL))
            {
                btnLink = new LinkButton();
                btnLink.ID = "lnkGridWizardCmdExportarExcel";
                btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                btnLink.CssClass = "menu_item_cmd";
                btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdExportarExcel"];
                btnLink.Visible = HasPermissionFor(CrmSecurity.CUSTOMER_EXPORT_EXCEL);
                btnLink.Click += new EventHandler(btnLinkExportarAExcel_Click);
                btnLink.OnClientClick = @"javascript: if (!window.CustomerSearchObj){window.CustomerSearchObj = new CustomerSearch();} return window.CustomerSearchObj.exportarExcel();";
                pnlGridWizardMenu.Controls.Add(btnLink);
                btnLink.Attributes.Add("aspnetid", btnLink.UniqueID);

                btnLink = new LinkButton();
                btnLink.ID = "lnkGridWizardCmdExportarCSV";
                btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                btnLink.CssClass = "menu_item_cmd";
                btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdExportarCSV"];
                btnLink.Visible = HasPermissionFor(CrmSecurity.CUSTOMER_EXPORT_EXCEL);
                btnLink.Click += new EventHandler(btnLinkExportarAExcel_Click);
                btnLink.OnClientClick = @"javascript: if (!window.CustomerSearchObj){window.CustomerSearchObj = new CustomerSearch();} return window.CustomerSearchObj.exportarExcel('csv');";
                pnlGridWizardMenu.Controls.Add(btnLink);
                btnLink.Attributes.Add("aspnetid", btnLink.UniqueID);
            }

            if (HasPermissionFor(CrmSecurity.CUSTOMER_ADDTO_DISTRIBUTIONLIST))
            {
                btnLink = new LinkButton();
                btnLink.ID = "lnkGridWizardCmdAgregarALista";
                btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                btnLink.CssClass = "menu_item_cmd";
                btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdAgregarAListaDistribucion"];
                btnLink.Click += new EventHandler(agregarContactosAListaButton_Click);
                pnlGridWizardMenu.Controls.Add(btnLink);
                btnLink.Attributes.Add("aspnetid", btnLink.UniqueID);
            }

            if (HasPermissionFor(CrmSecurity.CUSTOMER_ADDTO_CATEGORY))
            {
                btnLink = new LinkButton();
                btnLink.ID = "lnkGridWizardCmdAgregarCategoria";
                btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                btnLink.CssClass = "menu_item_cmd";
                btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdAgregarACategoria"];
                btnLink.Click += new EventHandler(agregarContactosACategoria_Click);
                pnlGridWizardMenu.Controls.Add(btnLink);
                btnLink.Attributes.Add("aspnetid", btnLink.UniqueID);
            }
        }

        private void btnLinkExportarAExcel_Click(object sender, EventArgs e)
        {
            GudarClientesSeleccionadosEnContexto();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write("btnLinkExportarAExcel_Click");
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        private void GudarClientesSeleccionadosEnContexto()
        {
            List<int> selectedIndexList = (List<int>)StoreHelper.GetObject(MiscClass.CustomerSearchCheckedItemsKey);
            if (selectedIndexList != null && !chkPnlGridWizardMenuAplicarATodoElFiltro.Checked) // Agrego la seleccion si no marco seleccionar a todos
            {
                CustomerSearchParamSession.Ids = selectedIndexList;
            }

            if (chkPnlGridWizardMenuAplicarATodoElFiltro.Checked)
            {
                CustomerSearchParamSession.Ids.Clear();
            }
        }

        private void btnLinkBorrarContactos_Click(object sender, EventArgs e)
        {
            try
            {
                GudarClientesSeleccionadosEnContexto();
                Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCustomerDelete, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void FiltroPanelVisibility()
        {
            if (paneles.Count == 0)
            {
                paneles.Add(pnlFiltroDocumento);
                paneles.Add(pnlFiltroCumpleanos);
                paneles.Add(pnlFiltroListaDistribucion);
                paneles.Add(pnlFiltroEstados);
                paneles.Add(pnlFiltroPais);
                paneles.Add(pnlFiltroCategorias);
                paneles.Add(pnlFiltroDatosDeVenta);
                paneles.Add(pnlFiltroCreacion);

                foreach (ListItem item in lstMasFiltros.Items)
                {
                    paneles[Convert.ToInt32(item.Value) - 1].CssClass = item.Selected ? "pnlFiltro displayBlock" : "pnlFiltro displayNone";
                }
            }
        }

        private List<Panel> paneles = new List<Panel>();

        private const int indDocumento = 1;
        private const int indCumpleanos = 2;
        private const int indListaDeDistribucion = 3;
        private const int indEstados = 4;
        private const int indNacionalidad = 5;
        private const int indCategorias = 6;
        private const int indDatosDeVenta = 7;
        private const int indCreacion = 8;

        private void LoadCbos()
        {
            if (lstMasFiltros.Items.Count == 0)
            {
                List<MaestroBase> filtros = new List<MaestroBase>();
                filtros.Add(new MaestroBase() { Id = indDocumento, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.Documento"] });
                filtros.Add(new MaestroBase() { Id = indCumpleanos, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.Cumpleanios"] });
                filtros.Add(new MaestroBase() { Id = indListaDeDistribucion, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.ListaDistribucion"] });
                filtros.Add(new MaestroBase() { Id = indEstados, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.Estados"] });
                filtros.Add(new MaestroBase() { Id = indNacionalidad, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.Nacionalidad"] });
                filtros.Add(new MaestroBase() { Id = indCategorias, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.Categorias"] });
                filtros.Add(new MaestroBase() { Id = indDatosDeVenta, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.DatosVenta"] });
                filtros.Add(new MaestroBase() { Id = indCreacion, Nombre = LocalizationProvider.Instance["Bo.SearchContacto.Filtros.Creacion"] });
                UIHelper.LoadLst(filtros, this.lstMasFiltros, string.Empty);
            }

            List<AdUser> vendedorList = WebServiceHelper.GetUsers(6, BasePage.CompanyId, string.Empty);
            UIHelper.LoadLst(vendedorList, lstVendedor, string.Empty, key: "UserName", value: "UserName");
            UIHelper.LoadLst(vendedorList, lstUsuarioCreador, string.Empty, key: "UserName", value: "UserName");

            List<MaestroBase> tipoDocumento = GetTipoDocumento(0);
            UIHelper.LoadLst(tipoDocumento, lstTipoDocumento, string.Empty);

            UIHelper.LoadEstados<TipoRegistroBitacora>(lstTipoRegistroBitacora);

            UIHelper.LoadLstRange(1, 31, this.lstCumpleDia);
            UIHelper.LoadLstMonth(this.lstCumpleMes);
            UIHelper.LoadLstRange(1930, 2030, this.lstCumpleAnio);

            List<Pais> pais = WebServiceHelper.GetPaises();
            UIHelper.LoadCbo(pais, cboPaisSearch, LocalizationProvider.Instance["DropDown.Todos"]);

            List<MaestroBase> listaDeDistribucionList = WebServiceHelper.GetListasDeDistribucion(BaseWebPage.CompanyId);
            UIHelper.LoadLst(listaDeDistribucionList, this.lstListaDistribucion);

            UIHelper.LoadEstados<TipoPdv>(cboTipoPdv, LocalizationProvider.Instance["DropDown.Todos"]);

            List<PuntoDeVenta> puntoVtaList = WebServiceHelper.GetPuntoDeVentaDto(new PuntoDeVentaSearch() { EmpresaId = BasePage.CompanyId });
            //UIHelper.LoadLst(puntoVtaList, this.lstPtoVtas);
            UIHelper.LoadLst(puntoVtaList, lstOrigenPuntoDeVenta);

            UIHelper.LoadEstados<TipoContactoOrigen>(this.lstOrigenContacto);

            UIHelper.LoadEstados<SexoEnum>(this.cboSexo, LocalizationProvider.Instance["DropDown.Todos"]);

            List<MaestroBase> categoriasList = this.GetCategorias(BaseWebPage.CompanyId);
            UIHelper.LoadLst(categoriasList, this.lstCategorias, string.Empty);

            // Estado
            UIHelper.LoadEstados<EstadoEmail>(this.lstEstadoEmail);

            // registros para la paginacion
            List<KeyValuePair<string, string>> opcionesParaPaginar = new List<KeyValuePair<string, string>>();
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("10", "10"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("20", "20"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("50", "50"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("100", "100"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("500", "500"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("1000", "1000"));
            opcionesParaPaginar.Add(new KeyValuePair<string, string>("0", LocalizationProvider.Instance["DropDown.Todos"]));
            UIHelper.LoadCbo(opcionesParaPaginar, this.cboRegistros, string.Empty, "Key", "Value");

            this.cboRegistros.SelectedValue = "100";

            // Estado Email
            UIHelper.LoadEstados<EstadoCliente>(this.lstEstado);

            // Campañas
            AccionDeMarketingSearch search = new AccionDeMarketingSearch();
            search.EmpresaId = BasePage.CompanyId;
            List<AccionDeMarketing> accionesList = WebServiceHelper.GetAccionesDeMarketing(search);
            UIHelper.LoadLst(accionesList, this.lstAccionMarketing, string.Empty);

            LoadComboProvincias();
            LoadComboPuntoDeVenta();
        }

        private void LoadComboProvincias()
        {
            if (this.cboPaisSearch.SelectedIndex >= 0)
            {
                List<MaestroBase> provincias = WebServiceHelper.GetProvincias(Convert.ToInt32(this.cboPaisSearch.SelectedValue));
                UIHelper.LoadLst(provincias, lstProvincia);
            }
        }

        private void LoadComboPuntoDeVenta()
        {
            if (this.cboTipoPdv.SelectedIndex >= 0)
            {
                PuntoDeVentaSearch pdvSearch = new PuntoDeVentaSearch() { EmpresaId = BasePage.CompanyId };
                if (this.cboTipoPdv.SelectedValue != UIHelper.cboNullValue)
                {
                    pdvSearch.Outlet = ((TipoPdv)Convert.ToInt32(this.cboTipoPdv.SelectedValue)) == TipoPdv.Outlet;
                }

                List<PuntoDeVenta> puntoVtaList = WebServiceHelper.GetPuntoDeVentaDto(pdvSearch);
                UIHelper.LoadLst(puntoVtaList, this.lstPtoVtas);
            }
        }

        private void Buscar()
        {
            try
            {
                // Elimino a los items chequeados si hicieron una búsqueda
                if (StoreHelper.GetObject(MiscClass.CustomerSearchCheckedItemsKey) != null)
                {
                    List<int> list = (List<int>)StoreHelper.GetObject(MiscClass.CustomerSearchCheckedItemsKey);
                    list.Clear();
                    StoreHelper.StoreObject(MiscClass.CustomerSearchCheckedItemsKey, null);
                }

                // Cargo un nuevo parámetro de búsqueda, el parametro se guarda en session porque lo usan las demas pantallas
                CustomerSearchParamSession = new CustomerSearchParam();
                CustomerSearchParamSession.SortIsAsc = SortDirectionViewState == SortDirection.Ascending;
                CustomerSearchParamSession.SortingField = SortExpressionViewState;
                CustomerSearchParamSession.PageSize = this.GridCustomer.PageSize;

                // Cargo el parámetro de búsqueda
                LoadSearchParams();

                //ClienteSearchResult searchResult = WebServiceHelper.GetCustomers(CustomerSearchParamViewState);
                //StoreHelper.StoreObject(MiscClass.CustomerSearchCacheKey, searchResult);
                //BindToGrid(searchResult);
                BindToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadSearchParams()
        {
            CustomerSearchParamSession.PageSize = Convert.ToInt32(this.cboRegistros.SelectedValue);
            CustomerSearchParamSession.EmpresaId = BasePage.CompanyId;
            CustomerSearchParamSession.Nombre = this.txtNombre.Text;
            CustomerSearchParamSession.Apellido = this.txtApellido.Text;
            CustomerSearchParamSession.Email = this.txtEmail.Text;
            CustomerSearchParamSession.ConEmail = this.tckConEmail.Checked;
            CustomerSearchParamSession.ConDocumento = this.tckConDocumento.Checked;
            CustomerSearchParamSession.ConVentas = this.tckConVentas.Checked;

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indDocumento))
            {
                CustomerSearchParamSession.TiposDocumento = UIHelper.GetIntFromInputLst(this.lstTipoDocumento);
                if (!String.IsNullOrEmpty(this.txtDNI.Text))
                {
                    CustomerSearchParamSession.Dni = Decimal.Parse(this.txtDNI.Text);
                }
            }

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indCumpleanos))
            {
                CustomerSearchParamSession.CumpleDias.AddRange(UIHelper.GetIntFromInputLst(this.lstCumpleDia));
                CustomerSearchParamSession.CumpleMeses.AddRange(UIHelper.GetIntFromInputLst(this.lstCumpleMes));
                CustomerSearchParamSession.CumpleAnios.AddRange(UIHelper.GetIntFromInputLst(this.lstCumpleAnio));

                CustomerSearchParamSession.FechaCumpleDesde = UIHelper.GetDateTimeFromInputText(this.txtCumpleDesde.Text);
                CustomerSearchParamSession.FechaCumpleHasta = UIHelper.GetDateTimeFromInputText(this.txtCumpleHasta.Text);
            }

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indListaDeDistribucion))
            {
                CustomerSearchParamSession.ListasDeDistribucion.AddRange(UIHelper.GetIntFromInputLst(this.lstListaDistribucion));
            }

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indEstados))
            {
                CustomerSearchParamSession.Estados.AddRange(UIHelper.GetIntFromInputLst(this.lstEstado));
                CustomerSearchParamSession.EstadosEmail.AddRange(UIHelper.GetIntFromInputLst(this.lstEstadoEmail));
                CustomerSearchParamSession.Sexo = UIHelper.GetIntFromInputCbo(this.cboSexo);
                CustomerSearchParamSession.TipoRegistroBitacora.AddRange(UIHelper.GetIntFromInputLst(this.lstTipoRegistroBitacora));
            }

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indNacionalidad))
            {
                CustomerSearchParamSession.NacionalidadId = UIHelper.GetIntFromInputCbo(this.cboPaisSearch);

                string lstProvinciaSelects = this.Request.Form[this.lstProvincia.UniqueID];
                if (!String.IsNullOrEmpty(lstProvinciaSelects))
                {
                    if (lstProvincia.Items.Count == 0)
                    {
                        LoadComboProvincias();
                    }

                    string[] lstProvinciaSelectsSplit = lstProvinciaSelects.Split(',');

                    foreach (ListItem item in this.lstProvincia.Items)
                    {
                        if (lstProvinciaSelectsSplit.Contains(item.Value))
                        {
                            item.Selected = true;
                        }
                    }

                    CustomerSearchParamSession.Provincias = UIHelper.GetIntFromInputLst(this.lstProvincia);
                }
            }

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indCategorias))
            {
                CustomerSearchParamSession.Categorias.AddRange(UIHelper.GetIntFromInputLst(lstCategorias));
            }

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indDatosDeVenta))
            {
                CustomerSearchParamSession.Factura = this.txtFactura.Text;

                CustomerSearchParamSession.TipoPdvDummy = UIHelper.GetIntFromInputCbo(this.cboTipoPdv);

                CustomerSearchParamSession.PuntosDeVenta.AddRange(UIHelper.GetIntFromInputLst(this.lstPtoVtas));

                DateTime fechaDesde;
                if (DateTime.TryParseExact(this.txtFechaCompraDesde.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out fechaDesde))
                {
                    CustomerSearchParamSession.FechaCompraDesde = fechaDesde;
                }

                DateTime fechaHasta;
                if (DateTime.TryParseExact(this.txtFechaCompraHasta.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out fechaHasta))
                {
                    CustomerSearchParamSession.FechaCompraHasta = fechaHasta;
                }

                CustomerSearchParamSession.Vendedores.AddRange(UIHelper.GetStrFromInputLst(this.lstVendedor));

                CustomerSearchParamSession.CodigosProducto.Clear();
                if (!String.IsNullOrEmpty(this.txtProductoMultipleSearch.Text))
                {
                    string[] splited = this.txtProductoMultipleSearch.Text.Split(',');
                    foreach (string s in splited)
                    {
                        if (!String.IsNullOrEmpty(s))
                        {
                            CustomerSearchParamSession.CodigosProducto.Add(s.Replace(" ", ""));
                        }
                    }
                }

                CustomerSearchParamSession.ProductoTemporadaLetra = this.txtProductoTemporadaLetra.Text;
                CustomerSearchParamSession.ProductoCodigoColor = this.txtProductoCodigoColor.Text;
                CustomerSearchParamSession.ProductoCodigoTalle = this.txtProductoCodigoTalle.Text;

                CustomerSearchParamSession.AccionesDeMarketingList.Clear();
                CustomerSearchParamSession.AccionesDeMarketingList.AddRange(UIHelper.GetIntFromInputLst(this.lstAccionMarketing));
            }

            if (UIHelper.IsItemSelected(this.lstMasFiltros, indCreacion))
            {
                DateTime fechaCreadoDesde;
                if (!String.IsNullOrEmpty(this.txtFechaCreadoDesde.Text))
                {
                    if (DateTime.TryParseExact(this.txtFechaCreadoDesde.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out fechaCreadoDesde))
                    {
                        CustomerSearchParamSession.FechaCreadoDesde = fechaCreadoDesde;
                    }
                }

                DateTime fechaCreadoHasta;
                if (!String.IsNullOrEmpty(this.txtFechaCreadoHasta.Text))
                {
                    if (DateTime.TryParseExact(this.txtFechaCreadoHasta.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out fechaCreadoHasta))
                    {
                        CustomerSearchParamSession.FechaCreadoHasta = fechaCreadoHasta;
                    }
                }

                CustomerSearchParamSession.OrigenPuntosDeVenta.AddRange(UIHelper.GetIntFromInputLst(this.lstOrigenPuntoDeVenta));

                CustomerSearchParamSession.OrigenContacto.AddRange(UIHelper.GetIntFromInputLst(this.lstOrigenContacto));

                CustomerSearchParamSession.CreadoresDelContacto.AddRange(UIHelper.GetStrFromInputLst(this.lstUsuarioCreador));
            }
        }

        private void LoadControlsFromSearchContext()
        {
            // Al seleccionar los valores mostrar el filtro

            this.txtNombre.Text = CustomerSearchParamSession.Nombre;
            this.txtApellido.Text = CustomerSearchParamSession.Apellido;
            this.txtEmail.Text = CustomerSearchParamSession.Email;
            this.tckConEmail.Checked = CustomerSearchParamSession.ConEmail;
            this.tckConDocumento.Checked = CustomerSearchParamSession.ConDocumento;
            this.tckConVentas.Checked = CustomerSearchParamSession.ConVentas;

            StringBuilder productoBuilder = new StringBuilder();
            string separador = string.Empty;
            if (CustomerSearchParamSession.CodigosProducto.Count > 0)
            {
                foreach (string s in CustomerSearchParamSession.CodigosProducto)
                {
                    productoBuilder.Append(separador);
                    productoBuilder.Append(s);
                    separador = ",";
                }
            }

            this.txtProductoMultipleSearch.Text = productoBuilder.ToString();

            this.txtProductoTemporadaLetra.Text = CustomerSearchParamSession.ProductoTemporadaLetra;
            this.txtProductoCodigoColor.Text = CustomerSearchParamSession.ProductoCodigoColor;
            this.txtProductoCodigoTalle.Text = CustomerSearchParamSession.ProductoCodigoTalle;

            if (CustomerSearchParamSession.Dni.HasValue)
            {
                this.txtDNI.Text = CustomerSearchParamSession.Dni.ToString();
            }

            UIHelper.SelectListBoxFromList(lstTipoDocumento, CustomerSearchParamSession.TiposDocumento);

            UIHelper.SelectListBoxFromList(lstCumpleDia, CustomerSearchParamSession.CumpleDias);
            UIHelper.SelectListBoxFromList(lstCumpleMes, CustomerSearchParamSession.CumpleMeses);
            UIHelper.SelectListBoxFromList(lstCumpleAnio, CustomerSearchParamSession.CumpleAnios);

            UIHelper.SelectListBoxFromList(lstListaDistribucion, CustomerSearchParamSession.ListasDeDistribucion);


            UIHelper.SelectListBoxFromList(lstEstado, CustomerSearchParamSession.Estados);
            UIHelper.SelectListBoxFromList(lstEstadoEmail, CustomerSearchParamSession.EstadosEmail);

            if (CustomerSearchParamSession.Sexo.HasValue)
            {
                this.cboSexo.SelectedValue = CustomerSearchParamSession.Sexo.Value.ToString();
            }

            if (CustomerSearchParamSession.NacionalidadId.HasValue)
            {
                this.cboPaisSearch.SelectedValue = CustomerSearchParamSession.NacionalidadId.Value.ToString();
            }

            if (lstProvincia.Items.Count == 0)
            {
                LoadComboProvincias();
            }

            if (CustomerSearchParamSession.TipoPdvDummy.HasValue)
            {
                cboTipoPdv.SelectedValue = CustomerSearchParamSession.TipoPdvDummy.Value.ToString();
            }

            UIHelper.SelectListBoxFromList(lstProvincia, CustomerSearchParamSession.Provincias);

            UIHelper.SelectListBoxFromList(lstCategorias, CustomerSearchParamSession.Categorias);

            UIHelper.SelectListBoxFromList(lstPtoVtas, CustomerSearchParamSession.PuntosDeVenta);

            UIHelper.SelectListBoxFromList(lstAccionMarketing, CustomerSearchParamSession.AccionesDeMarketingList);

            this.txtFactura.Text = CustomerSearchParamSession.Factura;
            if (CustomerSearchParamSession.FechaCompraDesde.HasValue)
            {
                this.txtFechaCompraDesde.Text = CustomerSearchParamSession.FechaCompraDesde.Value.ToString("dd/MM/yyyy");
            }

            if (CustomerSearchParamSession.FechaCompraHasta.HasValue)
            {
                this.txtFechaCompraHasta.Text = CustomerSearchParamSession.FechaCompraHasta.Value.ToString("dd/MM/yyyy");
            }

            if (CustomerSearchParamSession.FechaCreadoDesde.HasValue)
            {
                this.txtFechaCreadoDesde.Text = CustomerSearchParamSession.FechaCreadoDesde.Value.ToString("dd/MM/yyyy");
            }

            if (CustomerSearchParamSession.FechaCreadoHasta.HasValue)
            {
                this.txtFechaCreadoHasta.Text = CustomerSearchParamSession.FechaCreadoHasta.Value.ToString("dd/MM/yyyy");
            }

            UIHelper.SelectListBoxFromList(lstOrigenPuntoDeVenta, CustomerSearchParamSession.OrigenPuntosDeVenta);
            UIHelper.SelectListBoxFromList(lstOrigenContacto, CustomerSearchParamSession.OrigenContacto);

            UIHelper.SelectListBoxFromList(lstTipoRegistroBitacora, CustomerSearchParamSession.TipoRegistroBitacora);

            //
            // HABILITO LOS FILTROS SI YA ESTAN SELECCIONADOS EN EL CONTEXTO
            //
            //UIHelper.IsItemSelected(this.lstMasFiltros, indDocumento) // Tipo doc y DNI
            if (CustomerSearchParamSession.TiposDocumento.Count > 0 || CustomerSearchParamSession.Dni.HasValue)
            {
                lstMasFiltros.Items[indDocumento - 1].Selected = true;
            }

            //UIHelper.IsItemSelected(this.lstMasFiltros, indCumpleanos) dias y fechas
            if (CustomerSearchParamSession.CumpleDias.Count > 0 ||
                CustomerSearchParamSession.CumpleMeses.Count > 0 ||
                CustomerSearchParamSession.CumpleAnios.Count > 0 ||
                CustomerSearchParamSession.FechaCumpleDesde.HasValue ||
                CustomerSearchParamSession.FechaCumpleHasta.HasValue)
            {
                lstMasFiltros.Items[indCumpleanos - 1].Selected = true;
            }

            //UIHelper.IsItemSelected(this.lstMasFiltros, indListaDeDistribucion) // solo lista de distribucion
            if (CustomerSearchParamSession.ListasDeDistribucion.Count > 0)
            {
                lstMasFiltros.Items[indListaDeDistribucion - 1].Selected = true;
            }

            //UIHelper.IsItemSelected(this.lstMasFiltros, indEstados)
            if (CustomerSearchParamSession.Estados.Count > 0 ||
                CustomerSearchParamSession.EstadosEmail.Count > 0 ||
                CustomerSearchParamSession.Sexo.HasValue ||
                CustomerSearchParamSession.TipoRegistroBitacora.Count > 0)
            {
                lstMasFiltros.Items[indEstados - 1].Selected = true;
            }

            // UIHelper.IsItemSelected(this.lstMasFiltros, indNacionalidad)
            if (CustomerSearchParamSession.NacionalidadId.HasValue ||
                CustomerSearchParamSession.Provincias.Count > 0)
            {
                lstMasFiltros.Items[indNacionalidad - 1].Selected = true;
            }

            // UIHelper.IsItemSelected(this.lstMasFiltros, indCategorias)
            if (CustomerSearchParamSession.Categorias.Count > 0)
            {
                lstMasFiltros.Items[indCategorias - 1].Selected = true;
            }

            // UIHelper.IsItemSelected(this.lstMasFiltros, indDatosDeVenta)
            if (!String.IsNullOrEmpty(CustomerSearchParamSession.Factura) ||
                CustomerSearchParamSession.PuntosDeVenta.Count > 0 ||
                CustomerSearchParamSession.FechaCompraDesde.HasValue ||
                CustomerSearchParamSession.FechaCompraHasta.HasValue ||
                CustomerSearchParamSession.Vendedores.Count > 0 ||
                CustomerSearchParamSession.CodigosProducto.Count > 0 ||
                !String.IsNullOrEmpty(CustomerSearchParamSession.ProductoTemporadaLetra) ||
                !String.IsNullOrEmpty(CustomerSearchParamSession.ProductoCodigoColor) ||
                !String.IsNullOrEmpty(CustomerSearchParamSession.ProductoCodigoTalle) )
            {
                lstMasFiltros.Items[indDatosDeVenta - 1].Selected = true;
            }

            // UIHelper.IsItemSelected(this.lstMasFiltros, indCreacion)
            if (CustomerSearchParamSession.FechaCreadoDesde.HasValue ||
                CustomerSearchParamSession.FechaCreadoHasta.HasValue ||
                CustomerSearchParamSession.OrigenPuntosDeVenta.Count > 0 ||
                CustomerSearchParamSession.OrigenContacto.Count > 0 ||
                CustomerSearchParamSession.CreadoresDelContacto.Count > 0)
            {
                lstMasFiltros.Items[indCreacion - 1].Selected = true;
            }
        }

        private void BindToGrid()
        {
            int pageSize = Convert.ToInt32(cboRegistros.SelectedValue);
            if (pageSize == 0)
            {
                this.GridCustomer.AllowPaging = false;
            }
            else
            {
                this.GridCustomer.AllowPaging = true;
                this.CustomerSearchParamSession.PageSize = this.GridCustomer.PageSize = pageSize;
            }

            this.GridCustomer.DataSourceID = "CustomerObjectDs";
        }

        private void RememberOldValues()
        {
            if (!String.IsNullOrEmpty(this.hidCheckedRows.Value))
            {
                List<int> selectedRowsIds = (List<int>)StoreHelper.GetObject(MiscClass.CustomerSearchCheckedItemsKey);
                if (selectedRowsIds == null)
                {
                    selectedRowsIds = new List<int>();
                }

                string[] ids = this.hidCheckedRows.Value.Split('#');
                this.hidCheckedRows.Value = string.Empty;
                foreach (string id in ids)
                {
                    if (!String.IsNullOrEmpty(id))
                    {
                        int idInt = Convert.ToInt32(id);
                        if (!selectedRowsIds.Contains(idInt))
                        {
                            selectedRowsIds.Add(idInt);
                        }
                    }
                }

                StoreHelper.StoreObject(MiscClass.CustomerSearchCheckedItemsKey, selectedRowsIds);
            }
        }

        private void RePopulateValues()
        {
            List<int> categoryIDList = (List<int>)StoreHelper.GetObject(MiscClass.CustomerSearchCheckedItemsKey);
            if (categoryIDList != null)
            {
                foreach (GridViewRow row in GridCustomer.Rows)
                {
                    int index = (int)GridCustomer.DataKeys[row.RowIndex].Value;
                    if (categoryIDList.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)row.FindControl("chkSelectRow");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }

        public SearchCustomerObjDataSourceProvider CustomerSearchProvider { get; set; }

        protected void CustomerObjectDs_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            GridViewSearchObjectDataSource searchProvider = new GridViewSearchObjectDataSource();
            this.CustomerSearchProvider = new SearchCustomerObjDataSourceProvider();
            this.CustomerSearchProvider.SearchParam = this.CustomerSearchParamSession;
            this.CustomerSearchProvider.WebServiceHelper = this.WebServiceHelper;

            searchProvider.Provider = this.CustomerSearchProvider;
            e.ObjectInstance = searchProvider;
        }

        protected void GridCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    //    int temporadaId = Convert.ToInt32(this.GridTemporadas.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //    this.Response.Redirect(string.Format("/App/TemporadaEdit.aspx?Id={0}", temporadaId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    //int temporadaId = Convert.ToInt32(this.GridTemporadas.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //WebServiceHelper.EliminarTemporada(temporadaId);
                    //StoreHelper.GetObject(this.Session, MiscClass.CustomerSearchCacheKey);

                }
                else if (e.CommandName == "cmdAltaContacto")
                {
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCustomer_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            try
            {
                if (e.Exception != null)
                {
                    ExceptionManager.Instance.HandleException(e.Exception);
                    e.ExceptionHandled = true;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCustomer_DataBound(object sender, EventArgs e)
        {
            try
            {
                if (CustomerSearchProvider != null)
                {
                    ClienteSearchResult searchResult = CustomerSearchProvider.SearchResult;

                    if (searchResult != null && searchResult.TotalDeResultados > 0)
                    {
                        this.pnlResults.CssClass = "displayBlock";
                        this.imgExpandResults.ImageUrl = "/Images/icon_blockexpanded.png";
                        string resultStr = string.Format(LocalizationProvider.Instance["Bo.SearchContacto.ResultString"], searchResult.TotalDeResultados);
                        lblSearchResult.Text = resultStr;

                        RePopulateValues();
                    }
                    else
                    {
                        lblSearchResult.Text = LocalizationProvider.Instance["Bo.SearchContacto.NoResultsString"];
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCustomer_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridCustomer.PageIndex = e.NewPageIndex;

                BindToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCustomer_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                // Si es la misma columna
                SortDirection sortDirection = e.SortDirection;
                if (this.SortExpressionViewState == e.SortExpression)
                {
                    if (this.SortDirectionViewState == SortDirection.Ascending)
                    {
                        this.SortDirectionViewState = SortDirection.Descending;
                        sortDirection = SortDirection.Descending;
                    }
                    else
                    {
                        this.SortDirectionViewState = SortDirection.Ascending;
                        sortDirection = SortDirection.Ascending;
                    }
                }

                this.SortExpressionViewState = e.SortExpression;
                this.CustomerSearchParamSession.SortIsAsc = sortDirection == SortDirection.Ascending;
                this.CustomerSearchParamSession.SortingField = e.SortExpression;

                this.SortExpressionViewState = e.SortExpression;

                BindToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridCustomer_RowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    AddSortImage(e.Row);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void AddSortImage(GridViewRow headerRow)
        {
            if (this.CustomerSearchParamSession != null)
            {
                if (SortExpressionViewState != "Id")
                {
                    Int32 iCol = GetSortColumnIndex(SortExpressionViewState); //this.CustomerSearchParamSession.SortingField);//SortExpressionViewState);
                    if (-1 == iCol || iCol == 0)
                    {
                        return;
                    }
                    // Create the sorting image based on the sort direction.
                    Image sortImage = new Image();
                    if (SortDirectionViewState == SortDirection.Ascending)//this.CustomerSearchParamSession.SortIsAsc)//SortDirectionViewState == SortDirection.Ascending == )
                    {
                        sortImage.ImageUrl = "/Images/arrowup.png";
                        sortImage.AlternateText = "Ascending Order";
                    }
                    else
                    {
                        sortImage.ImageUrl = "/Images/arrowdown.png";
                        sortImage.AlternateText = "Descending Order";
                    }

                    // Add the image to the appropriate header cell.
                    headerRow.Cells[iCol].Controls.Add(sortImage);
                }
            }
        }

        private int GetSortColumnIndex(string expression)
        {
            int colIndex = -1;
            int i = 0;
            foreach (DataControlField field in this.GridCustomer.Columns)
            {
                if (field.SortExpression == expression)
                {
                    colIndex = i;
                    break;
                }

                i++;
            }

            return colIndex;
        }

        protected void GridCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (columnasParaGrillaListCurrent != null)
                {
                    //if (e.Row.RowType == DataControlRowType.Header)
                    //{
                    //    Control ctrlchkSelect = e.Row.FindControl("chkSelect");
                    //    if (ctrlchkSelect != null)
                    //    {
                    //        //((CheckBox)ctrlchkSelect).Checked = CustomerSearchParamSession.SearchSelectAll;
                    //    }
                    //}

                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        Cliente cliente = (Cliente)e.Row.DataItem;

                        // Bindeo la grilla con comandos
                        Panel pnlEngineCommand = (Panel)e.Row.FindControl("pnlEngineCommand");

                        FillRowCommandLinks(HttpContext.Current, cliente, pnlEngineCommand);

                        int tipoDocIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "TipoDocumentoId").Single().PosicionDestino;
                        if (cliente.TipoDocumentoId.HasValue)
                        {
                            foreach (ListItem liDocItem in this.lstTipoDocumento.Items)
                            {
                                if (Convert.ToInt32(liDocItem.Value) == cliente.TipoDocumentoId.Value)
                                {
                                    e.Row.Cells[tipoDocIndex].Text = liDocItem.Text;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            e.Row.Cells[tipoDocIndex].Text = string.Empty;
                        }

                        int estadoEmailIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "EstadoEmail").Single().PosicionDestino;
                        if (cliente.EstadoEmail.HasValue)
                        {
                            EstadoEmail estadoEmail = (EstadoEmail)cliente.EstadoEmail.Value;
                            e.Row.Cells[estadoEmailIndex].Text = UIHelper.GetEnumDescription(estadoEmail);
                        }
                        else
                        {
                            e.Row.Cells[estadoEmailIndex].Text = string.Empty;
                        }

                        int estadoIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "Estado").Single().PosicionDestino;
                        if (cliente.Estado.HasValue)
                        {
                            EstadoCliente estadoCliente = (EstadoCliente)cliente.Estado.Value;
                            e.Row.Cells[estadoIndex].Text = UIHelper.GetEnumDescription(estadoCliente);
                        }
                        else
                        {
                            e.Row.Cells[estadoIndex].Text = string.Empty;
                        }

                        int paisIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "Nacionalidad").Single().PosicionDestino;
                        if (cliente.NacionalidadId.HasValue)
                        {
                            int nacionalidadId = cliente.NacionalidadId.Value;
                            e.Row.Cells[paisIndex].Text = this.GetPaises().Where(p => p.Id == nacionalidadId).Single().Nombre;
                        }
                        else
                        {
                            e.Row.Cells[paisIndex].Text = string.Empty;
                        }

                        int provinciaIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "ProvinciaId").Single().PosicionDestino;
                        if (cliente.NacionalidadId.HasValue && cliente.ProvinciaId.HasValue)
                        {
                            int provinciaId = cliente.ProvinciaId.Value;
                            var provincia = this.GetProvincias(cliente.NacionalidadId.Value).Where(p => p.Id == provinciaId).SingleOrDefault();
                            if (provincia != null)
                                e.Row.Cells[provinciaIndex].Text = provincia.Nombre;
                            else
                            {
                                e.Row.Cells[provinciaIndex].Text = string.Empty;
                            }
                        }
                        else
                        {
                            e.Row.Cells[provinciaIndex].Text = string.Empty;
                        }

                        int origenIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "OrigenId").Single().PosicionDestino;
                        e.Row.Cells[origenIndex].Text = UIHelper.GetEnumDescription((TipoContactoOrigen)cliente.OrigenId);

                        int origenPuntoDeVentaIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "OrigenPuntoDeVentaId").Single().PosicionDestino;
                        if (cliente.OrigenPuntoDeVentaId.HasValue)
                        {
                            e.Row.Cells[origenPuntoDeVentaIndex].Text = this.GetPuntosDeVenta(cliente.EmpresaId).Where(p => p.Id == cliente.OrigenPuntoDeVentaId.Value).Single().Nombre;
                        }
                        else
                        {
                            e.Row.Cells[origenPuntoDeVentaIndex].Text = string.Empty;
                        }

                        if (cliente.Sexo.HasValue)
                        {
                            int sexoIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "Sexo").Single().PosicionDestino;
                            SexoEnum sexoEnum = (SexoEnum)cliente.Sexo.Value;
                            e.Row.Cells[sexoIndex].Text = UIHelper.GetEnumDescription(sexoEnum);
                        }

                        if (cliente.CantidadHijos.HasValue)
                        {
                            int cantHijosIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "CantidadHijos").Single().PosicionDestino;
                            ContactoCantidadHijos cantHijosEnum = (ContactoCantidadHijos)cliente.CantidadHijos.Value;
                            e.Row.Cells[cantHijosIndex].Text = UIHelper.GetEnumDescription(cantHijosEnum);
                        }

                        if (cliente.EdadHijoMenor.HasValue)
                        {
                            int edadHijosIndex = columnasParaGrillaListCurrent.Where(c => c.ColumnName == "EdadHijoMenor").Single().PosicionDestino;
                            ContactoEdadHijoMenor edadHijoEnum = (ContactoEdadHijoMenor)cliente.EdadHijoMenor.Value;
                            e.Row.Cells[edadHijosIndex].Text = UIHelper.GetEnumDescription(edadHijoEnum);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private const string cmdAltaContacto = "altaContacto";
        private const string cmdModificacionContacto = "modificacionContacto";
        private const string cmdEliminarContacto = "eliminarContacto";
        private const string cmdAgregarACategoria = "agregarContactoACategoira";
        private static void FillRowCommandLinks(HttpContext context, Cliente cliente, Panel pnlEngineCommand)
        {
            LinkButton btnLink = new LinkButton();
            btnLink.ID = "pnlEngineCommand_VerContacto_" + cliente.Id.ToString();
            btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            btnLink.CssClass = "menu_item_cmd";
            btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdVerContacto"];
            btnLink.CommandName = cmdAltaContacto;
            btnLink.CommandArgument = cliente.Id.ToString();
            btnLink.Click += new EventHandler(btnLink_Click);
            btnLink.OnClientClick = "javascript: window.location.href='" + context.Request.Url.GetLeftPart(UriPartial.Authority) + MiscClass.UrlCustomerEdit + "?Id=" + cliente.Id.ToString() + "'; return false;";
            pnlEngineCommand.Controls.Add(btnLink);

            //btnLink = new LinkButton();
            //btnLink.ID = "pnlEngineCommand_EditarContacto_" + cliente.Id.ToString();
            //btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            //btnLink.CssClass = "menu_item_cmd";
            //btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdEditarContacto"];
            //btnLink.CommandName = cmdModificacionContacto;
            //btnLink.CommandArgument = cliente.Id.ToString();
            //btnLink.Click += new EventHandler(btnLink_Click);
            //btnLink.OnClientClick = "javascript: window.location.href='" + context.Request.Url.GetLeftPart(UriPartial.Authority) + MiscClass.UrlCustomerEdit + "?Id=" + cliente.Id.ToString() + "'; return false;";
            //pnlEngineCommand.Controls.Add(btnLink);

            //btnLink = new LinkButton();
            //btnLink.ID = "pnlEngineCommand_EliminarContacto_" + cliente.Id.ToString();
            //btnLink.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            //btnLink.CssClass = "menu_item_cmd";
            //btnLink.Text = LocalizationProvider.Instance["Bo.SearchContacto.CmdEliminarContacto"]; ;
            //btnLink.CommandName = cmdEliminarContacto;
            //btnLink.CommandArgument = cliente.Id.ToString();
            //btnLink.OnClientClick = "javascript: window.location.href='" + context.Request.Url.GetLeftPart(UriPartial.Authority) + MiscClass.UrlCustomerEdit + "?Id=" + cliente.Id.ToString() + "'; return false;";
            //pnlEngineCommand.Controls.Add(btnLink);
        }

        static void btnLink_Click(object sender, EventArgs e)
        {
            try
            {
                HttpContext.Current.Response.Redirect(string.Format(MiscClass.UrlCustomerEdit + "?Id={0}", e.ToString()), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkDummyRefreshSelectedGridChecks_Click(object sender, EventArgs e)
        {
            try
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write("lnkDummyRefreshSelectedGridChecks_Click");
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();

            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkAplicarOrdenColumnas_Click(object sender, EventArgs e)
        {
            try
            {
                BindToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void repeaterColumnOrderSelector_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                ColumnasParaGrilla columnaParaGrilla = (ColumnasParaGrilla)e.Item.DataItem;

                CheckBox chkBox = e.Item.FindControl("chkRepeater") as CheckBox;
                if (chkBox != null)
                {
                    chkBox.Attributes.Add("columnName", columnaParaGrilla.ColumnName);
                    chkBox.Text = columnaParaGrilla.ColumnDescription;
                    chkBox.Checked = columnaParaGrilla.Visible;
                    chkBox.CssClass = "chkOrdenable";
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}